package com.copm.demonstrationsystem.service.housetypefeatures.impl;

import com.copm.demonstrationsystem.commons.response.ResponseStatus;
import com.copm.demonstrationsystem.commons.util.ImageUtils;
import com.copm.demonstrationsystem.config.SystemConfig;
import com.copm.demonstrationsystem.dao.housetypefeatures.HouseTypeDao;
import com.copm.demonstrationsystem.dao.housetypefeatures.HouseTypeImageDao;
import com.copm.demonstrationsystem.dao.housetypefeatures.RoomTypeDao;
import com.copm.demonstrationsystem.dto.housetypefeatures.HouseTypeImageReceiveDto;
import com.copm.demonstrationsystem.dto.housetypefeatures.HouseTypeImageResponseDto;
import com.copm.demonstrationsystem.dto.housetypefeatures.HouseTypeResponseDto;
import com.copm.demonstrationsystem.pojo.commons.Image;
import com.copm.demonstrationsystem.pojo.housetypefeatures.HouseType;
import com.copm.demonstrationsystem.pojo.housetypefeatures.HouseTypeImage;
import com.copm.demonstrationsystem.pojo.housetypefeatures.RoomType;
import com.copm.demonstrationsystem.service.housetypefeatures.HouseTypeFeaturesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author chuyunfei
 * @date: 2018/4/17
 * @description: 1、实现房间类型的增删改查； 2、实现户型的增删改查 3、实现户型图片的增加和删除
 */
@Service
public class HouseTypeFeaturesServiceImpl implements HouseTypeFeaturesService {

    @Autowired
    private SystemConfig config;

    private Logger logger = LoggerFactory.getLogger(HouseTypeFeaturesServiceImpl.class);
    //房间类型
    private RoomTypeDao roomTypeDao;
    //户型
    private HouseTypeDao houseTypeDao;
    //户型图片
    private HouseTypeImageDao houseTypeImageDao;

    @Override
    @Transactional
    public ResponseStatus addRoomType(String name){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        //判断该房间类型是否已经存在
        RoomType roomType = roomTypeDao.findByName(name);

        //如果该房间类型不存在
        if(roomType == null){
            //添加一个新的户型
            roomType = new RoomType(name);
            try{
                roomTypeDao.save(roomType);
                //返回状态为正常
                response.setStatue(1);
                logger.info("添加新的户型：" + name + " 成功！");
            }catch(Exception e){
                e.printStackTrace();
                logger.error("添加新的户型：" + name + " 失败！");
                response.setMessage("数据存储出错");
            }
        }else{
            logger.info("添加的户型：" + name + " 已经存在！");
            response.setMessage("这个房间类型已经存在了");
        }

        return response;
    }

    @Override
    @Transactional
    public ResponseStatus deleteRoomType(Long id){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        try{
            //删除这个户型
            roomTypeDao.delete(id);
            //同时删除这个户型所对应的户型图片
            houseTypeImageDao.deleteByRoomTypeId(id);
            //返回状态正常
            response.setStatue(1);
        }catch(Exception e){
            e.printStackTrace();
            logger.info("删除户型：" + id + " 失败！");
            response.setMessage("删除房间类型失败");
        }
        return response;
    }

    @Override
    public ResponseStatus getRoomTypes(){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        try{
            List<RoomType> roomTypes = roomTypeDao.findAll();
            boolean empty = roomTypes == null||roomTypes.size() == 0;
            if(empty){
                response.setMessage("还没有房间类型");
            }else{
                response.setData(roomTypes);
                response.setStatue(1);
            }
        }catch(Exception e){
            e.printStackTrace();
            response.setMessage("获取房间类型失败");
        }
        return response;
    }

    @Override
    @Transactional
    public ResponseStatus addHouseType(String name){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        HouseType houseType = new HouseType(name);
        try{
            houseTypeDao.save(houseType);
            response.setStatue(1);
        }catch(Exception e){
            e.printStackTrace();
            response.setMessage("数据存储失败");
        }
        return response;
    }

    @Override
    @Transactional
    public ResponseStatus deleteHouseType(Long id){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        try{
            //VR的删除确定
            HouseType houseType = houseTypeDao.findOne(id);
            if(houseType != null && houseType.getVrUrl() != null){
                response.setMessage("有重要的资料，请三思后再删除！");
                return response;
            }
            //删除户型
            houseTypeDao.delete(id);
            //删除户型的相关图片
            houseTypeImageDao.deleteByHouseTypeId(id);
            response.setStatue(1);
        }catch(Exception e){
            e.printStackTrace();
            response.setMessage("删除户型失败，不存在该数据或者持久层异常");
        }

        return response;
    }

    @Override
    public ResponseStatus getHouseTypes(){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        List<HouseType> houseTypes = houseTypeDao.findAll();

        boolean empty = houseTypes == null||houseTypes.size() == 0;
        if(empty){
            response.setMessage("还没有户型");
        }else{
            List<Object> responseHousetypeDtos = new ArrayList<>(houseTypes.size());

            //选择全部的户型的数据
            for(HouseType houseType : houseTypes){
                responseHousetypeDtos.add(getHouseType(houseType.getId()).getData());
            }
            //设置返回数据
            response.setData(responseHousetypeDtos);

            response.setStatue(1);
        }

        return response;
    }

    @Override
    public ResponseStatus getHouseType(Long id){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        HouseTypeResponseDto houseTypeResponseDto = new HouseTypeResponseDto();

        try{
            //获取户型对象
            HouseType houseType = houseTypeDao.findOne(id);
            if(houseType == null){
                throw new RuntimeException("没有这个户型");
            }
            houseTypeResponseDto.setHouseType(houseType);

            //获取该户型所对应的样板间图对象集合
            List<HouseTypeImage> sampleRoom = houseTypeImageDao.findSampleRoomByHouseTypeId(id);
            //如果为null的话将不就行转换，否则出现空指针异常
            houseTypeResponseDto.setHouseSampleRooms(sampleRoom == null ? new ArrayList<HouseTypeImageResponseDto>() : changeImageToResponse(sampleRoom));

            //获取该户型所对应的平面图对象集合
            List<HouseTypeImage> plansImage = houseTypeImageDao.findPlansImageByHouseTypeId(id);
            houseTypeResponseDto.setHousePlans(plansImage == null ? new ArrayList<HouseTypeImageResponseDto>() : changeImageToResponse(plansImage));

            //将数据返回
            response.setData(houseTypeResponseDto);

            response.setStatue(1);
        }catch(Exception e){
            e.printStackTrace();
            response.setMessage("获取指定户型失败");
        }

        return response;
    }

    @Override
    @Transactional
    public ResponseStatus addHouseTypeImage(HouseTypeImageReceiveDto imageReceiveDto,MultipartFile file) {

//        try{
//            System.out.println(Arrays.toString(ImageUtils.storeAndCompressionImage(ImageUtils.getImageDir(),file)));
//        }catch(FileNotFoundException e){
//            e.printStackTrace();
//        }
        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);
        try{
            //选取所有上传的户型
            Long houseTypeId = imageReceiveDto.getHouseTypeId();
            if(houseTypeId == null){
                throw new RuntimeException("没有户型的ID");
            }

            //选取图片的房间类型
            Long roomTypeId = imageReceiveDto.getRoomTypeId();
            //兼容平面图
            if(roomTypeId == -1){
                List<HouseTypeImage> planImages = houseTypeImageDao.findPlansImageByHouseTypeId(houseTypeId);
                //该户型原来就有平面图
                if(planImages != null && planImages.size()>=1){
                    for(HouseTypeImage image:planImages){
                        //删除物理图片
                        String imageDir = ImageUtils.getImageDir();
                        ImageUtils.delete(imageDir,image.getImage().getFileName());
                    }
                    //删除原有的数据
                    houseTypeImageDao.deleteAllByHouseTypeIdAndAndImageKind(houseTypeId,2L);
                }
                roomTypeId = 0L;
            }

            //存储该图片
            String dir = ImageUtils.getImageDir();

            String[] paths = ImageUtils.storeAndCompressionImage(dir,file);

            if(paths == null){
                throw new RuntimeException("图片存储失败了！");
            }

            //存储这个图片的记录
            HouseTypeImage houseTypeImage = new HouseTypeImage(roomTypeId,houseTypeId,imageReceiveDto.getKind(),new Image(paths[0],paths[1],paths[2]));
            houseTypeImageDao.save(houseTypeImage);

            response.setStatue(1);
        }catch(Exception e){
            e.printStackTrace();
            response.setMessage("添加户型图片出错：" + e.getMessage());
        }

        return response;
    }

    @Override
    @Transactional
    public ResponseStatus deleteHouseTypeImage(Long id){

        ResponseStatus response = new ResponseStatus();
        response.setStatue(0);

        try{
            HouseTypeImage image = houseTypeImageDao.findOne(id);

            //删除物理图片
            String imageDir = ImageUtils.getImageDir();

            ImageUtils.delete(imageDir,image.getImage().getFileName());

            //删除记录
            houseTypeImageDao.delete(id);

            response.setStatue(1);
        }catch(Exception e){
            response.setMessage("删除图片出错");
        }

        return response;
    }

    /**
     * 1、将户型图片进行响应前的响应
     *
     * @param houseTypeImages：数据库查出来的原始数据
     *
     * @return ：转换后的数据
     */
    private List<HouseTypeImageResponseDto> changeImageToResponse(List<HouseTypeImage> houseTypeImages){
        //对平面图进行转换
        List<HouseTypeImageResponseDto> output = new ArrayList<>(houseTypeImages.size());

        //房间类型
        String roomTypeName = null;

        //文件名称，对相应的图片的图片的路径进行转换，将文件名称转换为可以直接进行访问的网络图片地址
        String fileName = null;
        String middle = null;
        String min = null;

        RoomType roomType = null;

        for(HouseTypeImage houseTypeImage : houseTypeImages){

            roomType = roomTypeDao.findOne(houseTypeImage.getRoomTypeId());

            if(roomType == null){
                roomTypeName = null;
            }else{
                roomTypeName = roomType.getName();
            }

            //获取图片文件名称
            fileName = houseTypeImage.getImage().getFileName();
            middle = houseTypeImage.getImage().getMiddle();
            min = houseTypeImage.getImage().getMin();

            //转换图片的路径，使其可以直接被访问
            houseTypeImage.getImage().setFileName("http://"+config.getServerIp()+":"+config.getServerPort()+ "/" + config.getApplicationName() + "/image/" + fileName);
            houseTypeImage.getImage().setMiddle("http://"+config.getServerIp()+":"+config.getServerPort()+ "/" + config.getApplicationName() + "/image/" + middle);
            houseTypeImage.getImage().setMin("http://"+config.getServerIp()+":"+config.getServerPort()+ "/" + config.getApplicationName() + "/image/" + min);
            output.add(new HouseTypeImageResponseDto(houseTypeImage,roomTypeName));
        }

        return output;
    }

    @Autowired
    public void setRoomTypeDao(RoomTypeDao roomTypeDao){
        this.roomTypeDao = roomTypeDao;
    }

    @Autowired
    public void setHouseTypeDao(HouseTypeDao houseTypeDao){
        this.houseTypeDao = houseTypeDao;
    }

    @Autowired
    public void setHouseTypeImageDao(HouseTypeImageDao houseTypeImageDao){
        this.houseTypeImageDao = houseTypeImageDao;
    }
}
